package com.szbmyoubao.app.view.dialog

import android.content.DialogInterface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.timer.tickFlow
import com.ellecity06.common.base.BaseBottomDialogFragment
import com.ellecity06.common.helper.AudioHelper
import com.ellecity06.common.helper.SoundRecorder
import com.ellecity06.common.ktx.gone
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.DialogAudioRecorderBinding
import kotlinx.coroutines.Job
import java.io.File

/**
 * @author ellecity06
 * @time 2025/3/13 18:01
 * @des
 */
class AudioRecorderDialog(val onSelect: (filePath: String) -> Unit) : BaseBottomDialogFragment<DialogAudioRecorderBinding>(), View.OnClickListener,
    AudioHelper.AudioPlayListener {
    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DialogAudioRecorderBinding {
        return DialogAudioRecorderBinding.inflate(inflater, container, false)
    }

    private var audioHelper: AudioHelper? = null

    /**
     * 是否正在录制
     */
    private var isRecorder = false

    /**
     * 是否录制完成
     */
    private var isComplete = false
    private var fileName: String? = null
    private var soundRecorder: SoundRecorder? = null
    override fun initialize() {
//        binding.voiceView.apply {
//            duration = 150
//
//            start()
//        }
        setState()
        setAudioPlayState(false)
        binding.tvStart.setOnClickListener(this)
        binding.ivPlay.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.ivClose.setOnClickListener(this)
    }

    private fun setState() {
//        binding.ivRecorder.setImageResource(if (isRecorder) R.mipmap.icon_voice_pause else R.mipmap.icon_voice_play)
        binding.tvStart.text = (if (isRecorder) "停止录制" else "开始录制")
        binding.layoutMusic.visibility = if (isComplete) View.VISIBLE else View.GONE
        if (isComplete && fileName != null) {
            try {
                binding.tvFileName.text = File(fileName).name
                binding.tvFileSize.text = "${time}s"
            } catch (e: Exception) {

            }

        }
    }

    private var tickFlow: Job? = null
    private var time = 0
    private val maxSec = 30
    private val minSec = 10
    private fun onDecibelUpdate(db: Double) {
//        logD("当前分贝: %.2f dB".format(db))
        var db2 = db.toInt() + 50
        if (db2 < 0) db2 = 0
        val body = if (db > 100) 100 else db2
        if (isResumed) {
            requireActivity().runOnUiThread {
                binding.voiceView.apply {
                    duration = 150
                    addBody(body)
                    start()
                }
            }
        }


    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            binding.ivClose.id -> {
                if (fileName != null) {
                    showAlert(content = "已有录音，确定要关闭放弃吗") {
                        dismiss()
                    }
                } else {
                    dismiss()
                }
            }

            binding.ivPlay.id -> {
                if (audioHelper == null) {
                    audioHelper = AudioHelper(this)
                }
                logD("文件名字=filename=${fileName}")
                audioHelper?.start(fileName!!)
            }

            binding.tvConfirm.id -> {
                if (fileName == null) {
                    ToastUtils.show("请先录音")
                    return
                }
                onSelect.invoke(fileName!!)
                dismiss()
            }

            binding.tvStart.id -> {
                if (isRecorder) {
                    fileName = soundRecorder!!.stopRecording()
                    isRecorder = false
                    recorderComplete()
                } else {
                    binding.voiceView.reset()
                    soundRecorder = soundRecorder ?: SoundRecorder {
                        onDecibelUpdate(it)
                    }
                    soundRecorder!!.startRecording()
                    isRecorder = true

                    binding.voiceView.visibility = View.VISIBLE
                    binding.pbDgDown.visibility = View.VISIBLE
                    binding.layoutTime.visibility = View.VISIBLE
                    binding.layoutMusic.gone()
                    lifecycleScope.launchWhenCreated {
                        time = 0
                        tickFlow = tickFlow {
                            binding.pbDgDown.progress = time
                            if (time < 10) {
                                binding.tvStartTime.text = "00:0$time"
                            } else {
                                binding.tvStartTime.text = "00:$time"
                            }
                            if (time >= maxSec) {
                                fileName = soundRecorder!!.stopRecording()
                                isRecorder = false
                                setState()
                                recorderComplete()
                                tickFlow?.cancel()
                                return@tickFlow
                            }
                            time++
                        }
                    }
                }
                setState()
            }
        }
    }

    /**
     * 录制完成
     */
    private fun recorderComplete() {
        tickFlow?.cancel()
        binding.voiceView.visibility = View.GONE
        binding.pbDgDown.visibility = View.GONE
        binding.layoutTime.visibility = View.GONE
        // 判断一下当前录制的时间
        // 判断一下当前录制的时间
        if (time < minSec) {
            ToastUtils.show("当前录制声音小于10秒，请重新开始录制")
            if (fileName != null) {
                File(fileName).delete()
            }
        } else {
            isComplete = true
        }
        setState()
    }

    private fun setAudioPlayState(isPlay: Boolean) {
//        binding.ivPlay.setImageResource(if (isPlay) R.mipmap.icon_voice_pause else R.mipmap.icon_voice_play)
    }

    override fun onPause() {
        super.onPause()
        audioHelper?.pause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        release()
    }

    private fun release() {
        tickFlow?.cancel()
        tickFlow = null
        binding.voiceView.stop()
        audioHelper?.stopAllVoice()
        audioHelper = null
        soundRecorder?.stopRecording()
        soundRecorder = null
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        release()

    }

    override fun onAudioStart() {
        logD("onAudioStart")
        setAudioPlayState(true)
    }

    override fun onAudioPause() {
        logD("onAudioPause")
        setAudioPlayState(false)
    }

    override fun onAudioReStart() {
        logD("onAudioReStart")
        setAudioPlayState(true)
    }

    override fun onAudioStop() {
        logD("onAudioStop")
        setAudioPlayState(false)
    }
}